package com.valuegroup.smarttodo.ui.todo.habit;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.common.BaseRecyclerAdapter;
import com.valuegroup.smarttodo.common.BaseViewHolder;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.HabitEvent;
import com.valuegroup.smarttodo.data.vo.AppCustomCfg;
import com.valuegroup.smarttodo.data.vo.HabitAndOrderVo;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.ui.todo.task.detail.TaskDetailActivity;
import com.valuegroup.smarttodo.util.AlertUtils;
import com.valuegroup.smarttodo.util.Cfg;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * 待办>习惯-主页
 */
public class HabitFragment extends Fragment {
    private static final String TAG = HabitFragment.class.getSimpleName();
    @BindView(R.id.todo_habit_list_recycler)
    RecyclerView recyclerView;

    private Unbinder unbinder;
    private HabitAdapter adapter;
    private AppCustomCfg cfg;
    private boolean initFinish;

    public static HabitFragment newInstance() {
        return new HabitFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_habit, container, false);
        unbinder = ButterKnife.bind(this, view);
        cfg = Cfg.getCfg(getContext());
        initFinish = true;

        assert recyclerView != null;
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        adapter = new HabitAdapter(view.getContext(), loadData(), multiTypeSupport);
        recyclerView.setAdapter(adapter);


        setHasOptionsMenu(true);
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //refreshData(data);
        refreshAllData();
    }

    /**
     * 更新列表中某条数据
     * 没有指定的刷新内容时，刷新整个列表
     *
     * @param intent
     */
    private void refreshData(Intent intent) {
        if (intent == null) {
            refreshAllData();
            return;
        }

        long id = intent.getLongExtra(TaskDetailActivity.PARAMS_KEY, 0);
        int position = intent.getIntExtra(TaskDetailActivity.PARAMS_POSITION, 0);

        if (id == 0) {
            refreshAllData();
            return;
        }

        // 刷新列表中当前操作记录
        HabitAndOrderVo data = ServiceFactory.getInstance().getHabitService().convertHabitAndOrderVoForGroup(id);
        adapter.refreshData(position, data);

        // 平移到指定位置
        recyclerView.smoothScrollToPosition(position);
    }

    /**
     * 更新列表所有数据
     */
    private void refreshAllData() {
        // 刷新列表数据
        adapter.refreshListData(loadData());
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(0);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        /*if (isVisibleToUser && initFinish) {
            refreshAllData();
        }*/
    }

    /**
     * 读取所有数据
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private List<HabitAndOrderVo> loadData() {
        return ServiceFactory.getInstance().getHabitService().findHabitAndGroupVo(cfg.isHabitHideFinish());
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        //先clear()一下, 这样按钮就只有Fragment中设置的自己的了, 不会有Activity中的按钮.
        menu.clear();

        inflater.inflate(R.menu.menu_habit, menu);
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        menu.findItem(R.id.habit_item3).setTitle(!cfg.isHabitHideFinish() ? R.string.habit_m3 : R.string.habit_m3_o);
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        switch (item.getItemId()) {
            case R.id.habit_item1:
                // 添加习惯组
                startActivityForResult(new Intent(getContext(), HabitOrderSetActivity.class), 1003);
                break;
            case R.id.habit_item2:
                // 习惯项管理
                startActivityForResult(new Intent(getContext(), HabitManageActivity.class), 1004);
                break;
            case R.id.habit_item3:
                // 隐藏已完成项
                cfg.setHabitHideFinish(!cfg.isHabitHideFinish());
                Cfg.saveCfg(getContext(), cfg);

                refreshAllData();
                break;
            default:
                break;
        }
        return true;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    class HabitAdapter extends BaseRecyclerAdapter<HabitAndOrderVo> {

        HabitAdapter(Context context, List<HabitAndOrderVo> data, MultiTypeSupport multiType) {
            super(context, data, multiType);
        }

        @Override
        public void bindView(BaseViewHolder v, HabitAndOrderVo data, int position) {

            if (data.isOrder()) {
                LinearLayout rootLayout = v.getView(R.id.rootLayout);
                rootLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(view.getContext(), HabitOrderActivity.class);
                        intent.putExtra(HabitOrderActivity.PARAMS_KEY, data.getOrderId());
                        intent.putExtra(HabitOrderActivity.PARAMS_POSITION, position);
                        startActivityForResult(intent, 1001);
                    }
                });

                v.setViewVisibility(R.id.tagFinish, data.isOrderFinish());
                v.setText(R.id.labTitle, data.getOrderTitle());
            } else {

                AppCompatCheckBox chkFinish = v.getView(R.id.chkFinish);
                chkFinish.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (b) {
                            // 更新打卡事件，并查询打卡次数
                            if (b != data.isEventFinish()) {
                                HabitEvent event = ServiceFactory.getInstance().getHabitService().doClockInDate(data.getRelateId());
                                if (event == null) {
                                    AlertUtils.showToast(getContext(), "数据异常！");
                                }
                                Integer[] arr = ServiceFactory.getInstance().getHabitService().findClockInDate(data.getRelateId());
                                data.setEventFinish(true);
                                data.setEventClockInDate(event.getClockInDate());
                                data.setEventTotalCount(arr[0]);
                                data.setEventFinishCount(arr[1]);
                            }

                            String subCount = String.format(getResources().getString(R.string.habit_sub_count), data.getEventTotalCount(), data.getEventFinishCount());
                            v.setText(R.id.labRemind, subCount);
                            v.setViewVisibility(R.id.labRemind, true);
                        } else {
                            if (b != data.isEventFinish() && data.getEventId() != null) {
                                ServiceFactory.getInstance().getHabitService().doUnfinish(data.getEventId());
                                data.setEventFinish(false);
                                data.setEventClockInDate(null);
                            }

                            v.setViewVisibility(R.id.labRemind, false);
                        }

                    }
                });


                v.getView(R.id.rootLayout).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showDialog(data.getHabitId());
                    }
                });

                // 优先级
                ImageView imgQuadrant = v.getView(R.id.tagQuadrant);
                imgQuadrant.setImageResource(AppStatus.QuadrantTagArr[data.getQuadrant()]);

                String subTime = String.format(getResources().getString(R.string.lab_minute), data.getHabitPreMinute());
                v.setText(R.id.labTitle, data.getHabitTitle());
                v.setText(R.id.labSubtitle, data.getHabitSubTitle());
                v.setText(R.id.labMinute, subTime);
//                if (data.getHabitEmoji() != null) {
//                    v.setImageResource(R.id.tagEmoji, data.getHabitEmoji());
//                }
                chkFinish.setChecked(data.isEventFinish());
            }
        }

    }

    private BaseRecyclerAdapter.MultiTypeSupport multiTypeSupport = new BaseRecyclerAdapter.MultiTypeSupport<HabitAndOrderVo>() {
        @Override
        public int getLayoutId(List<HabitAndOrderVo> datas, int position) {
            if (position == 0) {
                return R.layout.item_default_header;
            } else if (position == (datas.size() + 1)) {
                return R.layout.item_default_bottom;
            } else {
                HabitAndOrderVo item = datas.get(position - 1);
                if (item.isOrder()) {
                    return R.layout.item_habit_group;
                } else {
                    return R.layout.item_habit;
                }
            }
        }

        @Override
        public int getAppendHeadLayoutSize() {
            return 1;
        }

        @Override
        public int getAppendBottomLayoutSize() {
            return 1;
        }

        @Override
        public boolean isBodyLayout(int dataSize, int position) {
            if (position == 0 || position == (dataSize + 1)) {
                return false;
            } else {
                return true;
            }
        }
    };


    private void showDialog(Long id) {
        if (mShareDialog == null) {
            initShareDialog();
        }
        initDialogData(id);
        mShareDialog.show();
    }

    private void initDialogData(Long id) {


        // 修改为通过习惯项直接查询，这样可以查询到历史打卡数据
        //List<HabitEvent> data = ServiceFactory.getInstance().getHabitService().findHabitEventForRelate(rid);
        List<HabitEvent> data = ServiceFactory.getInstance().getHabitService().findHabitEvent(id);

        // 刷新列表数据
        habitSigninAdapter.refreshListData(data);

        // 跳转至当前日期所在位置
        habitSigninRecycler.post(new Runnable() {
            @Override
            public void run() {
                String today = DateUtils.date2str(new Date(), DateUtils.F40);
                for (int position = 0; position < data.size(); position++) {
                    if (DateUtils.date2str(data.get(position).getScheduleDt(), DateUtils.F40).equals(today)) {
                        //habitSigninRecycler.smoothScrollToPosition(position);
                        //平滑到操作项
                        ((LinearLayoutManager) habitSigninRecycler.getLayoutManager()).scrollToPositionWithOffset(position, 0);
                        break;
                    }
                }
            }
        });
    }

    private Dialog mShareDialog;
    private RecyclerView habitSigninRecycler;
    private HabitSigninAdapter habitSigninAdapter;

    /**
     * 初始化弹出框
     */
    private void initShareDialog() {
        mShareDialog = new Dialog(getContext(), R.style.dialog_bottom_full);
        mShareDialog.setCanceledOnTouchOutside(true);
        mShareDialog.setCancelable(true);
        Window window = mShareDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.share_animation);
        View view = View.inflate(getContext(), R.layout.dialog_habit_signin, null);

        habitSigninAdapter = new HabitSigninAdapter(getContext(), new ArrayList<>());
        habitSigninRecycler = view.findViewById(R.id.listSignin);
        habitSigninRecycler.setHasFixedSize(true);
        habitSigninRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        habitSigninRecycler.setAdapter(habitSigninAdapter);

        view.findViewById(R.id.btnClose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mShareDialog != null && mShareDialog.isShowing()) {
                    mShareDialog.dismiss();
                    // 补卡后数据要刷新
                    refreshAllData();
                }
            }
        });

        window.setContentView(view);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
    }

}
